package nature.nano.control.script.parse;

import java.util.ArrayList;
import java.util.List;

import nature.nano.component.Strings;

// TODO: optimize
public class StringHelper {
	
	public static String mergeScripts(String[] scripts) {
		StringBuilder builder = new StringBuilder();
		for (String script : scripts) {
			builder.append(script);
			builder.append(Strings.semicolon);
		}
		return builder.toString();		
	}
	
	public static List<String> split(String content, String reg) {
		List<String> list = new ArrayList<String>();
		if (content == null || content.length() == 0) {
			return list;
		}
		
		int current = 0;
		int searched = 0;
		do {
			int point = content.indexOf(reg, searched);
			if (point < 0) {
				list.add(content.substring(current, content.length()));
				break;
			} else {
				if (!bracketsComplete(content.substring(current, point))) {
					searched = point + 1;
					continue;
				} else {
					list.add(content.substring(current, point));
					current = point + 1;
					searched = current;
				}
			}
		} while (true);
		
		return list;
	}
	
	private static boolean bracketsComplete(String content) {
		int lbCount = count(content, Strings.lb);
		int rbCount = count(content, Strings.rb);
		return lbCount == rbCount;
	}
	
	private static int count(String content, String reg) {
		int count = 0;
		int current = 0;
		
		do {
			int point = content.indexOf(reg, current);
			if (point < 0) {
				break;
			} else {
				count++;
				current = point + 1;
			}
		} while(true);
		
		return count;
	}
	
	public static void main(String[] args) {
		String content = "ScriptInputter[script=FolderScanner > FolderSorter(F).uncoded(U) > DailyCutter > DumpFileSource > LogicOutput > SqlLoaderDataWriter;U > Printer[file=log_u1.txt];] > InlineCommentFilter > ScriptLineParser > AccepterAssembly; A > uu";
		List<String> result = split(content, Strings.semicolon);
		for (String it : result) {
			System.out.println(it);
		}
	}
	
}
